package edu.whu.demo.controller;


import edu.whu.demo.entity.Item;
import edu.whu.demo.service.ItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Api(description = "商品管理")
@RestController
@RequestMapping("items")
public class ItemController {
    @Autowired
    ItemService itemService;

    // get: localhost:8888/items/1
    @ApiOperation("根据Id查询商品")
    @GetMapping("/{id}")
    public ResponseEntity<Item> getItem(@ApiParam("商品Id")@PathVariable long id){
        Item result = itemService.getItem(id);
        if(result==null) {
            return ResponseEntity.noContent().build();
        }else{
            return ResponseEntity.ok(result);
        }
    }

    // get: localhost:8888/items
    // get: localhost:8888/items?name=笔记本
    // get: localhost:8888/items?name=笔记本&&surplus=true
    @ApiOperation("根据条件查询商品")
    @GetMapping("")
    public ResponseEntity<List<Item>> findItem(@ApiParam("商品名称")String name, @ApiParam("是否有余量")Boolean surplus){
        List<Item> result = itemService.findItems(name, surplus);
        return ResponseEntity.ok(result);
    }

    @ApiOperation("添加商品")
    @PostMapping("")
    public ResponseEntity<Item> addItem(@RequestBody Item item){
        Item result = itemService.addItem(item);
        return ResponseEntity.ok(result);
    }

    @ApiOperation("修改商品")
    @PutMapping("/{id}")
    public ResponseEntity<Void> updateItem(@PathVariable long id,@RequestBody Item item){
        itemService.updateItem(id,item);
        return ResponseEntity.ok().build();
    }

    @ApiOperation("删除商品")
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteItem(@PathVariable long id){
        itemService.deleteItem(id);
        return ResponseEntity.ok().build();
    }
}
